<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺名称" prop="sellerId"><el-select v-model="queryParams.sellerId" placeholder="请选择店铺名称" clearable :disabled="nowUser != null"><el-option v-for="sellerItem in sellerList" :key="sellerItem.sellerId" :label="sellerItem.storeName" :value="sellerItem.sellerId"/></el-select></el-form-item>
      <el-form-item label="商品名称" prop="goodsName"><el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery"/></el-form-item>
      <el-form-item label="商品类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择商品类型" clearable>
          <el-option v-for="typeItem in typeList" :key="typeItem.typeId" :label="typeItem.typeName" :value="typeItem.typeId"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"><el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['shopping:goods:all']">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['shopping:goods:all']">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['shopping:goods:all']">删除</el-button></el-col>
      <el-col :span="1.5"><el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['shopping:goods:all']">导出</el-button></el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getGoodsList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" stripe="stripe" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品编号" align="center" prop="goodsId" sortable/>
<!--      <el-table-column label="商品编号" align="center" type="index" fixed="left" width="150"/>-->
      <el-table-column label="店铺名称" align="center" prop="seller.storeName" sortable/>
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="商品评分" align="center" prop="star" :formatter="starFormat" />
      <el-table-column label="商品类型" align="center" prop="typeId" :formatter="typeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['shopping:goods:all']" >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['shopping:goods:all']" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getGoodsList"/>

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺名称" prop="sellerId"><el-select v-model="form.sellerId" :disabled="nowUser != null" placeholder="请选择店铺名称"><el-option v-for="sellerItem in sellerList" :key="sellerItem.sellerId" :label="sellerItem.storeName" :value="sellerItem.sellerId"></el-option></el-select></el-form-item>
        <el-form-item label="商品图片" prop="goodsImage"><image-upload v-model="form.goodsImage" property="goods"/></el-form-item>
        <el-form-item label="商品名称" prop="goodsName"><el-input v-model="form.goodsName" placeholder="请输入商品名称" /></el-form-item>
        <el-form-item label="商品类型" prop="typeId"><el-select v-model="form.typeId" placeholder="请选择商品类型"><el-option v-for="typeItem in typeList" :key="typeItem.typeId" :label="typeItem.typeName" :value="typeItem.typeId"/></el-select></el-form-item>
        <el-form-item label="商品评分" prop="star"><el-rate v-model="form.star"></el-rate></el-form-item>
        <el-form-item label="商品描述"><editor v-model="form.memo" :min-height="192"/></el-form-item>
      </el-form>
      <el-divider content-position="center">商品规格信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5"><el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddGoodsDetail" v-hasPermi="['shopping:goods:all']">添加</el-button></el-col>
        <el-col :span="1.5"><el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteGoodsDetail" v-hasPermi="['shopping:goods:all']">删除</el-button></el-col>
      </el-row>
      <el-table :data="detailList" :row-class-name="rowGoodsDetailIndex" @selection-change="handleGoodsDetailSelectionChange" ref="goodsDetail">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" prop="index" min-width="50"/>
        <el-table-column label="规格名称" prop="detailName" min-width="150"><template slot-scope="scope"><el-input v-model="scope.row.detailName" placeholder="请输入规格名称" /></template></el-table-column>
        <el-table-column label="规格数量" prop="detailNum" min-width="150"><template slot-scope="scope"><el-input v-model="scope.row.detailNum" placeholder="请输入规格数量" /></template></el-table-column>
        <el-table-column label="规格价格" prop="detailPrice" min-width="150"><template slot-scope="scope"><el-input v-model="scope.row.detailPrice" placeholder="请输入规格价格" /></template></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, getGoods, delGoods, addGoods, updateGoods } from "@/api/shopping/goods";
import { listSeller } from "@/api/user/seller";
import { getLoginType } from '@/utils/auth'
import { listType } from "@/api/shopping/type";

export default {
  name: "Goods",
  dicts: ['sys_yes_no', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsList: [],
      // 商家数据
      sellerList: [],
      // 规格数据
      detailList: [],
      // 类型数据
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前登录者
      nowUser: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sellerId: null,
        goodsName: null,
        typeId: null,
        memo: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sellerId: [{ required: true, message: "店铺名称不能为空", trigger: "blur" }],
        goodsName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        phone: [{ required: true, message: "商家电话不能为空", trigger: "blur" }],
        status: [{ required: true, message: "店铺状态不能为空", trigger: "change" }],
        memo: [{ required: true, message: "商品描述不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    let type = getLoginType();
    if (type === 'seller') {
      this.nowUser = this.$store.state.user;
      this.queryParams.sellerId = this.nowUser.id;
    }
    this.getGoodsList();
    this.getSellerList();
    this.getTypeList();
  },
  methods: {
    /** 查询商品列表 */
    getGoodsList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询卖家列表 */
    getSellerList() {
      this.loading = true;
      let type = getLoginType();
      if (type === 'seller') {
        this.sellerList.push({"sellerId": this.nowUser.id, storeName: this.nowUser.name})
      } else {
        listSeller().then(response => {
          this.sellerList = response.rows;
          this.loading = false;
        });
      }
    },
    /** 查询类型列表 */
    getTypeList() {
      this.loading = true;
      listType().then(response => {
        this.typeList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        sellerId: null,
        goodsImage: null,
        goodsName: null,
        typeId: null,
        star: null,
        memo: null,
        delFlag: null
      };
      this.resetForm("form");
      if (this.nowUser != null) {
        this.form.sellerId = this.nowUser.id;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getGoodsList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids
      getGoods(goodsId).then(response => {
        this.form = response.data;
        this.detailList = response.data.detailList;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.detailList = this.detailList;
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getGoodsList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getGoodsList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + goodsIds + '"的数据项？').then(function() {
        return delGoods(goodsIds);
      }).then(() => {
        this.getGoodsList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    typeFormat(row, column) {return this.typeList[row.typeId - 1].typeName},
    starFormat(row, column) {return row.star.toFixed(1)},
    /** 商品规格序号 */
    rowGoodsDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 商品规格添加按钮操作 */
    handleAddGoodsDetail() {
      let obj = {};
      obj.detailName = "";
      obj.detailNum = "";
      obj.detailPrice = "";
      this.detailList.push(obj);
    },
    /** 商品规格删除按钮操作 */
    handleDeleteGoodsDetail() {
      if (this.checkedGoodsDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的商品规格数据");
      } else {
        const goodsDetailList = this.detailList;
        const checkedGoodsDetail = this.checkedGoodsDetail;
        this.detailList = goodsDetailList.filter(function(item) {
          return checkedGoodsDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleGoodsDetailSelectionChange(selection) {
      this.checkedGoodsDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('shopping/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
